<template>
  <div class="container">
    <div class="main">
      <p>发表攻略</p>
      <span>分享你的个人游记,让更多人看到哦!</span>
      <el-form ref="form" :model="form" label-width="90px">
        <!-- 在 Form 组件中，每一个表单域由一个 Form-Item 组件构成 -->
        <el-form-item class="title">
          <el-input v-model="form.title" placeholder="请输入标题"></el-input>
        </el-form-item>

        <!-- 富文本编辑框 -->
        <!-- useCustomImageHandler当布尔值为true时就可以自定义事件处理图片的上传 -->
        <!-- 子组件传出一个事件，这边用imgUpload接收并处理图片的上传 -->
        <!-- editorToolbar这是工具栏的设置 -->
        <el-form-item>
          <VueEditor
            ref="vueEditor"
            v-model="form.content"
            :useCustomImageHandler="true"
            @image-added="imgUpload"
            :editorToolbar="customToolbar"
          />
        </el-form-item>


        <!-- fetch-suggestions：输入框文字变化时候就会触发，类似input事件 -->
        <div class="selector">
          <div class="cities">选择城市</div>
          <!-- 选择城市输入框 -->
          <el-form-item>
            <el-autocomplete
              class="inline-input"
              v-model="form.city"
              :fetch-suggestions="queryCitySearch"
              @select="handleCitySelect"
              @blur="handleCityBlur"
              placeholder="请搜索游玩城市"
            ></el-autocomplete>
          </el-form-item>
        </div>

        <!-- 发布 -->
        <el-form-item>
          <el-button type="primary" @click="handlesubmit">发布</el-button>&nbsp;或者
          <a href="#">保存到草稿</a>
        </el-form-item>
      </el-form>
    </div>
    <div class="aside">
      <h4>草稿箱</h4>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        content: "",
        title: "",
        city:""
      },
      //   工具栏的配置
      customToolbar: [
        ["bold", "italic", "underline"],
        [{ list: "ordered" }, { list: "bullet" }],
        ["image", "code-block"]
      ],
      cities:[]
    };
  },
  methods: {
    // 这里是富文本框添加图片触发的函数
    imgUpload(file, Editor, cursorLocation, resetUploader) {
      // An example of using FormData
      // NOTE: Your key could be different such as:
      // formData.append('file', file)

      // file 使我们要上传的文件
      // Editor 是我们正在使用的编辑器
      // cursorLocation 这是子组件获取到的当前光标位置
      // restUploader 这是当你处理完了所有数据,应该重置这个上传的组件

      var formData = new FormData();
      formData.append("files", file);

      this.$axios({
        url: "/upload",
        method: "POST",
        data: formData
      })
        .then(res => {
          console.log(res);
          const {data} = res;  
          let url = this.$axios.defaults.baseURL + data[0].url; // Get url from response
          Editor.insertEmbed(cursorLocation, "image", url);
          resetUploader();
        })
        .catch(err => {
          console.log(err);
        });
    },

    // 输入城市的事件，根据输入的关键字请求接口返回相关城市
    // value是输入框的值
    // cb是回调函数，调用函数时必须传入一个数组
    queryCitySearch(value,cb){
      // 如果输入框为空,则返回空列表
      if(!value.trim()){
        return cb([]);
      }
      // 输入框输入时发送请求
      this.$axios({
        url:"/airs/city",
        params:{
          name:value
        }
      }).then(res=>{
        const {data} = res.data;
        // console.log(data);
        // 因为返回的数组是有带有"市"，但我们的下拉列表没有，所以要改造一哈返回来的数组
        // 利用map遍历数组，并返回新数组
        this.cities = data.map(element=>{
          element.value = element.name.replace("市","");
          return element;
        })
        cb(this.cities);
      })
    },
    // 若输入框失去焦点，默认选中第一个
    handleCityBlur(){
      // 若什么也没有输入，则返回
      if(this.cities.length === 0) return;
      this.form.city = this.cities[0].value;
    },
    // 下拉选择城市时触发
    // item市选中的下拉列表数据
    handleCitySelect(item){
      this.form.city = item.value;
    },
    handlesubmit(){
      this.$axios({
        url:"/posts",
        method:"post",
        data:this.form,
        headers: {
          "Content-Type": "application/json",
          Authorization:`Bearer ${this.$store.state.user.userInfo.token}`
        }
      }).then(res=>{
        console.log(res);
        // const {data} = res;
        if(res.status == 200){
          this.$message.success("新增成功");
          this.form.title = "";
          this.form.content = "";
          this.form.city = "";
        }
      })
    }
  }
};
</script>

<style lang="less" scoped>
.container {
  width: 1000px;
  margin: 0 auto;
  padding: 20px 0;
  position: relative;
  .main {
    width: 750px;
    p {
      font-size: 24px;
      margin-bottom: 10px;
      margin-right: 65px;
    }
    span {
      display: block;
      font-size: 12px;
      color: #999;
      margin-bottom: 20px;
    }
  }
  /deep/ .el-form-item__content {
    margin: 0 !important;
    vertical-align: middle;
  }
  /deep/.selector {
    display: flex;
    justify-content: start;
    align-items: center;
    .cities {
      margin-right: 10px;
      margin-bottom: 22px;
      font-size: 16px !important;
      color: black !important;
    }
  }
  a {
    color: orange;
    font-size: 14px;
  }
  .aside {
    border: 1px solid #ccc;
    width: 205px;
    position: absolute;
    top: 20px;
    left: 800px;
    padding: 10px;
    h4 {
      font-weight: 400;
      color: #666;
      margin-bottom: 10px;
    }
  }
}
</style>
